"""
文件处理工具模块
提供文件上传、验证、命名等功能
"""
import os
import uuid
import mimetypes
from datetime import datetime

def allowed_file(filename, allowed_extensions):
    """
    检查文件类型是否被允许
    
    Args:
        filename: 文件名
        allowed_extensions: 允许的扩展名集合
        
    Returns:
        bool: 文件类型是否被允许
    """
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions

def get_file_size(file):
    """
    获取文件大小（字节）
    
    Args:
        file: 文件对象
        
    Returns:
        int: 文件大小
    """
    # 保存当前位置
    current_position = file.tell()
    
    # 移动到文件末尾
    file.seek(0, os.SEEK_END)
    file_size = file.tell()
    
    # 恢复到之前的位置
    file.seek(current_position)
    
    return file_size

def generate_unique_filename(original_filename):
    """
    生成唯一的文件名
    
    Args:
        original_filename: 原始文件名
        
    Returns:
        str: 唯一文件名
    """
    # 获取文件扩展名
    _, extension = os.path.splitext(original_filename)
    
    # 生成唯一标识符
    unique_id = str(uuid.uuid4())
    
    # 创建时间戳
    timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
    
    # 组合文件名
    new_filename = f"{timestamp}_{unique_id}{extension}"
    
    return new_filename

def secure_filename_with_uuid(filename):
    """
    生成安全的文件名（使用UUID）
    
    Args:
        filename: 原始文件名
        
    Returns:
        str: 安全的文件名
    """
    # 获取文件扩展名
    _, extension = os.path.splitext(filename)
    
    # 生成UUID作为文件名
    filename_uuid = str(uuid.uuid4())
    
    return f"{filename_uuid}{extension.lower()}"

def get_file_extension(filename):
    """
    获取文件扩展名（小写）
    
    Args:
        filename: 文件名
        
    Returns:
        str: 文件扩展名
    """
    _, extension = os.path.splitext(filename)
    return extension.lower()

def get_file_mime_type(filename):
    """
    获取文件MIME类型
    
    Args:
        filename: 文件名
        
    Returns:
        str: MIME类型
    """
    mime_type, _ = mimetypes.guess_type(filename)
    return mime_type

def is_image_file(filename):
    """
    检查是否为图像文件
    
    Args:
        filename: 文件名
        
    Returns:
        bool: 是否为图像文件
    """
    image_extensions = {'png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'tiff', 'svg'}
    return get_file_extension(filename) in image_extensions

def is_video_file(filename):
    """
    检查是否为视频文件
    
    Args:
        filename: 文件名
        
    Returns:
        bool: 是否为视频文件
    """
    video_extensions = {'mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm', 'm4v'}
    return get_file_extension(filename) in video_extensions

def get_readable_file_size(size_bytes):
    """
    将字节大小转换为人类可读的格式
    
    Args:
        size_bytes: 字节大小
        
    Returns:
        str: 人类可读的文件大小
    """
    for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024.0

def ensure_directory_exists(directory_path):
    """
    确保目录存在，如果不存在则创建
    
    Args:
        directory_path: 目录路径
    """
    if not os.path.exists(directory_path):
        os.makedirs(directory_path)

def delete_file_safely(file_path):
    """
    安全删除文件
    
    Args:
        file_path: 文件路径
        
    Returns:
        bool: 删除是否成功
    """
    try:
        if os.path.exists(file_path):
            os.remove(file_path)
            return True
        return False
    except Exception as e:
        return False

def copy_file(source_path, destination_path):
    """
    复制文件
    
    Args:
        source_path: 源文件路径
        destination_path: 目标文件路径
        
    Returns:
        bool: 复制是否成功
    """
    import shutil
    try:
        # 确保目标目录存在
        destination_dir = os.path.dirname(destination_path)
        ensure_directory_exists(destination_dir)
        
        shutil.copy2(source_path, destination_path)
        return True
    except Exception as e:
        return False

def move_file(source_path, destination_path):
    """
    移动文件
    
    Args:
        source_path: 源文件路径
        destination_path: 目标文件路径
        
    Returns:
        bool: 移动是否成功
    """
    import shutil
    try:
        # 确保目标目录存在
        destination_dir = os.path.dirname(destination_path)
        ensure_directory_exists(destination_dir)
        
        shutil.move(source_path, destination_path)
        return True
    except Exception as e:
        return False

def get_directory_size(directory_path):
    """
    获取目录大小
    
    Args:
        directory_path: 目录路径
        
    Returns:
        int: 目录大小（字节）
    """
    total_size = 0
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename)
            if os.path.exists(filepath):
                total_size += os.path.getsize(filepath)
    return total_size

def clean_directory(directory_path, days=7):
    """
    清理目录中指定天数前的文件
    
    Args:
        directory_path: 目录路径
        days: 天数阈值
        
    Returns:
        dict: 清理统计信息
    """
    import time
    
    current_time = time.time()
    threshold_time = current_time - (days * 24 * 60 * 60)
    
    files_deleted = 0
    total_size_deleted = 0
    
    for dirpath, dirnames, filenames in os.walk(directory_path):
        for filename in filenames:
            filepath = os.path.join(dirpath, filename)
            
            # 检查文件修改时间
            if os.path.getmtime(filepath) < threshold_time:
                try:
                    file_size = os.path.getsize(filepath)
                    os.remove(filepath)
                    files_deleted += 1
                    total_size_deleted += file_size
                except Exception as e:
                    continue
    
    return {
        'files_deleted': files_deleted,
        'total_size_deleted': total_size_deleted,
        'total_size_deleted_readable': get_readable_file_size(total_size_deleted)
    }

# 导出
__all__ = [
    'allowed_file',
    'get_file_size',
    'generate_unique_filename',
    'secure_filename_with_uuid',
    'get_file_extension',
    'get_file_mime_type',
    'is_image_file',
    'is_video_file',
    'get_readable_file_size',
    'ensure_directory_exists',
    'delete_file_safely',
    'copy_file',
    'move_file',
    'get_directory_size',
    'clean_directory'
]